package com.demo.Queue;

import org.omg.CORBA.Request;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class RequestQueue {

	private static final int MAX_LIMIT = 20;
	private static final int LIMIT = 10;

	private final Queue<Request> queue = new ArrayBlockingQueue<>(MAX_LIMIT);
	ReentrantLock lock = new ReentrantLock();
	Condition condition = lock.newCondition();

	public Request get() {
		Request result = null;
		lock.lock();
		try {
			while (queue.isEmpty()) {
				condition.await();
			}
			result = queue.poll();
			condition.signalAll();
		} catch (InterruptedException e) {
			condition.signalAll();
		} finally {
			lock.unlock();
		}
		return result;
	}

	public void put(Request request) {
		lock.lock();
		try {
			while (queue.size() >= LIMIT) {
				condition.await();
			}
			queue.offer(request);
			condition.signalAll();
		} catch (InterruptedException e) {
			condition.signalAll();
		} finally {
			lock.unlock();
		}
	}
}
